package bsc.war.handler;

import bsc.ejb.entity.SRM;
import bsc.ejb.entity.SRMTopic;
import bsc.ejb.entity.ScoreView;
import bsc.ejb.entity.Topic;
import bsc.ejb.entity.TopicScoreView;
import bsc.ejb.metadata.Colorimetry;
import bsc.ejb.metadata.Framework;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import bsc.war.model.Score;
import bsc.war.service.BSCUtils;
import bsc.war.service.ScoreCardUtils;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.lowagie.text.pdf.PdfTable;
import java.awt.Color;
import java.net.URL;
import java.text.NumberFormat;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 *
 * @author Memo
 */
public class SRMAgenda extends AbstractController {

    public SRMAgenda() {
    }

    @Override
    protected ModelAndView handleRequestInternal(
                           HttpServletRequest request,
                           HttpServletResponse response) throws Exception {

        try {
            DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");
            Long idSRM = request.getParameter("srm") != null && NumberUtils.isNumber(request.getParameter("srm")) ? Long.parseLong(request.getParameter("srm")) : null;
            /*Long idScoreView = request.getParameter("scoreView") != null && NumberUtils.isNumber(request.getParameter("scoreView")) ? Long.parseLong(request.getParameter("scoreView")) : null;*/
            SRM srm = delegate.findSRM(idSRM);
            ScoreView scoreView = srm.getScoreView();
            List<Topic> srmTopics = delegate.findTopic(srm);

            response.setContentType("application/pdf");
            Document document = new Document(PageSize.A4.rotate());
            document.setMargins(10, 10, 10, 10);

            Font titleFont = new Font();
            titleFont.setFamily("Arial");
            titleFont.setSize(20);
            titleFont.setStyle(Font.BOLD);

            Font headerFont = new Font();
            headerFont.setFamily("Arial");
            headerFont.setSize(10);
            headerFont.setStyle(Font.BOLD);

            Font bodyFont = new Font();
            bodyFont.setFamily("Arial");
            bodyFont.setSize(10);

            PdfWriter.getInstance(document, response.getOutputStream());
            document.open();
            document.addTitle(srm.getName());

            Image image = Image.getInstance(new URL(BSCUtils.getServerPath(request)+((Framework)request.getSession(true).getAttribute("framework")).getLogo()));
            image.setAlignment(Image.ALIGN_RIGHT);
            image.setIndentationRight(20);
            image.scalePercent(50f, 50f);
            document.add(image);

            Paragraph memo = new Paragraph("AGENDA\n",titleFont);
            memo.setAlignment(Paragraph.ALIGN_CENTER);
            document.add(memo);
            
            Paragraph title = new Paragraph(srm.getName()+"\n\n\n");
            title.setAlignment(Paragraph.ALIGN_CENTER);
            document.add(title);

            PdfPTable resume = new PdfPTable(4);
            resume.setWidthPercentage(95);
            PdfPCell resumeHeader = new PdfPCell();
            resumeHeader.setBackgroundColor(new BaseColor(187, 221, 92));
            resumeHeader.setPhrase(new Phrase("Lugar",headerFont));
            resume.addCell(resumeHeader);
            resume.addCell(new Phrase(srm.getPlace() != null ? srm.getPlace() : "No especificado",bodyFont));
            resumeHeader.setPhrase(new Phrase("Fecha y Hora",headerFont));
            resume.addCell(resumeHeader);
            if( srm.getSRMDate()==null && srm.getSRMHour()==null )
                resume.addCell(new Phrase("No especificadas",bodyFont));
            else
                resume.addCell( new Phrase((srm.getSRMDate() != null ? srm.getSRMDate() + " " : "" )
                    +(srm.getSRMHour() != null ? srm.getSRMHour() : ""),bodyFont));
            resumeHeader.setPhrase(new Phrase("Responsable",headerFont));
            resume.addCell(resumeHeader);
            resume.addCell(new Phrase(srm.getResponsable() != null ? srm.getResponsable() : "No especificado",bodyFont));
            resumeHeader.setPhrase(new Phrase("Tiempo Total",headerFont));
            resume.addCell(resumeHeader);
            resume.addCell(new Phrase(srm.getExpectedTime() != null ? ""+srm.getExpectedTime() + "hrs" : "No especificado",bodyFont));
            document.add(resume);
            document.add(new Paragraph("\n\n\n"));
            
            // TEMAS A TRATAR            
            PdfPCell header = new PdfPCell();
            resumeHeader.setHorizontalAlignment(PdfTable.ALIGN_CENTER);
            
            PdfPTable pendingTopics = new PdfPTable(6);
            pendingTopics.setWidthPercentage(95);
            pendingTopics.setWidthPercentage(95);
            pendingTopics.setHorizontalAlignment(PdfTable.ALIGN_CENTER);
            header.setColspan(6);
            header.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            header.setPhrase(new Phrase("Temas a tratar",headerFont));
            header.setBackgroundColor(new BaseColor(187, 221, 92));
            pendingTopics.addCell(header);
            resumeHeader.setBackgroundColor(new BaseColor(224, 240, 183));
            resumeHeader.setPhrase(new Phrase("Tema",headerFont));
            pendingTopics.addCell(resumeHeader);
            resumeHeader.setPhrase(new Phrase("Acuerdo",headerFont));
            pendingTopics.addCell(resumeHeader);
            resumeHeader.setPhrase(new Phrase("Responsable del acuerdo",headerFont));
            pendingTopics.addCell(resumeHeader);
            resumeHeader.setPhrase(new Phrase("Estatus",headerFont));
            pendingTopics.addCell(resumeHeader);
            resumeHeader.setPhrase(new Phrase("Avance",headerFont));
            pendingTopics.addCell(resumeHeader);
            resumeHeader.setPhrase(new Phrase("Tiempo estimado",headerFont));
            pendingTopics.addCell(resumeHeader);
            
            
            PdfPTable topicScoreCards = new PdfPTable(5);
            topicScoreCards.setWidthPercentage(95);
            topicScoreCards.setHorizontalAlignment(PdfTable.ALIGN_CENTER);
            header.setColspan(5);
            header.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            header.setPhrase(new Phrase("Indicadores / Scorecards actuales",headerFont));
            header.setBackgroundColor(new BaseColor(187, 221, 92));
            topicScoreCards.addCell(header);
            resumeHeader.setBackgroundColor(new BaseColor(224, 240, 183));
            resumeHeader.setPhrase(new Phrase("Tema",headerFont));
            topicScoreCards.addCell(resumeHeader);
            resumeHeader.setPhrase(new Phrase("Descripción",headerFont));
            topicScoreCards.addCell(resumeHeader);
            resumeHeader.setPhrase(new Phrase("Responsable del tema",headerFont));
            topicScoreCards.addCell(resumeHeader);
            resumeHeader.setPhrase(new Phrase("Score",headerFont));
            topicScoreCards.addCell(resumeHeader);
            resumeHeader.setPhrase(new Phrase("Tiempo estimado",headerFont));
            topicScoreCards.addCell(resumeHeader);

            PdfPTable otherTopics = new PdfPTable(4);
            otherTopics.setWidthPercentage(95);
            otherTopics.setHorizontalAlignment(PdfTable.ALIGN_CENTER);
            header.setColspan(4);
            header.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            header.setPhrase(new Phrase("Otros temas relevantes",headerFont));
            header.setBackgroundColor(new BaseColor(187, 221, 92));
            otherTopics.addCell(header);
            resumeHeader.setBackgroundColor(new BaseColor(224, 240, 183));
            resumeHeader.setPhrase(new Phrase("Tema",headerFont));
            otherTopics.addCell(resumeHeader);
            resumeHeader.setPhrase(new Phrase("Descripción",headerFont));
            otherTopics.addCell(resumeHeader);
            resumeHeader.setPhrase(new Phrase("Responsable del tema",headerFont));
            otherTopics.addCell(resumeHeader);
            resumeHeader.setPhrase(new Phrase("Tiempo estimado",headerFont));
            otherTopics.addCell(resumeHeader);
            
            for (Topic topic : srmTopics) {
                SRMTopic srmTopic = delegate.findSRMTopic(srm, topic);
                TopicScoreView topicScoreView = delegate.findTopicScoreView(topic, scoreView);
                
                if( topicScoreView.getType() != TopicScoreView.Type.COMPLETED){
                    pendingTopics.addCell(new Phrase(srmTopic.getTopic().getTopic(),bodyFont));
                    pendingTopics.addCell(new Phrase(srmTopic.getDeal(),bodyFont));
                    pendingTopics.addCell(new Phrase(srmTopic.getResponsable(),bodyFont));
                    pendingTopics.addCell(new Phrase(ScoreCardUtils.topicStatus(topicScoreView.getType()),bodyFont));
                    pendingTopics.addCell(new Phrase(srmTopic.getProgress() != null ? srmTopic.getProgress().toString() : "No especificado",bodyFont));
                    pendingTopics.addCell(new Phrase(srmTopic.getExpectedTime() != null ? srmTopic.getExpectedTime() + "min" : "",bodyFont));
                }

                if(topic.getScoreCard() != null){
                    topicScoreCards.addCell(new Phrase(srmTopic.getTopic().getTopic(),bodyFont));
                    topicScoreCards.addCell(new Phrase(srmTopic.getDescription(),bodyFont));
                    topicScoreCards.addCell(new Phrase(srmTopic.getResponsable(),bodyFont));
                    Score score = ScoreCardUtils.calculateScore(delegate, ScoreCardUtils.getSystemComparation(request), topic.getScoreCard(), ScoreCardUtils.getSystemDate(request));
                    Colorimetry colorimetry = delegate.findColorimetry(topic.getScoreCard(), score.getScore());
                    PdfPCell scoreCell = new PdfPCell();
                    Font font = FontFactory.getFont("Arial");
                    font.setSize(10);
                    font.setColor(new BaseColor(Color.decode("#"+colorimetry.getColor())));
                    NumberFormat nf = NumberFormat.getPercentInstance();
                    String scoreFormat = nf.format(score.getScore());                    
                    scoreCell.setPhrase(new Phrase(scoreFormat,font));
                    topicScoreCards.addCell(scoreCell);
                    topicScoreCards.addCell(new Phrase(srmTopic.getExpectedTime() != null ? srmTopic.getExpectedTime() + "min" : "",bodyFont));
                } else {
                    otherTopics.addCell(new Phrase(srmTopic.getTopic().getTopic(),bodyFont));
                    otherTopics.addCell(new Phrase(srmTopic.getDescription(),bodyFont));
                    otherTopics.addCell(new Phrase(srmTopic.getResponsable(),bodyFont));
                    otherTopics.addCell(new Phrase(srmTopic.getExpectedTime() != null ? srmTopic.getExpectedTime() + "min" : "",bodyFont));
                }
            }
            document.add(pendingTopics);
            document.add(new Paragraph("\n\n\n"));
            document.add(topicScoreCards);
            document.add(new Paragraph("\n\n\n"));
            document.add(otherTopics);
            document.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
}
